<?php


namespace App\Service;

use App\Utility\McHelper;
use EasySwoole\Log\Logger;
use EasySwoole\Oss\QiNiu\Auth;
use EasySwoole\Oss\QiNiu\Storage\UploadManager;
use Swoole\Coroutine\Channel;


class UploadService
{

    public static function uploadToQiniu($file, $user_id = 0, $prefix = 'qienpet')
    {
        $config = \EasySwoole\EasySwoole\Config::getInstance()->getConf('OSS');
        $channel = new Channel(2345);
        $storage = strtoupper('qiniu');
        go(function () use ($config, $storage, $file, $user_id, $prefix, $channel) {

            $auth = new Auth($config[$storage]['AK'], $config[$storage]['SK']);
            $bucket = $config[$storage]['BUCKET'];
            $temp_name = $file->getTempName();
            $raw_filename = $file->getClientFilename();
            $ext = McHelper::getFileExt($raw_filename);
            $key = date('Y-m-d') . '/' . $prefix . '/' . McHelper::generateRandomFileName($user_id) . '.' . $ext;
            $token = $auth->uploadToken($bucket, $key);
            $upManager = new UploadManager();
            list($ret, $error) = $upManager->putFile($token, $key, $temp_name);
            if ($error) {
                \EasySwoole\EasySwoole\Logger::getInstance()->error('QINIU_UPLOAD_ERROR:' . $error);
            } else {
                $ret['ext'] = $ext;
                $ret['name'] = $raw_filename;
                $ret['md5'] = md5_file($temp_name);
                $ret['sha1'] = sha1_file($temp_name);
                $ret['filesize'] = $file->getSize();
                $channel->push($ret);
            }
        });
        $result = $channel->pop();
        if (!empty($result)) {
            $base_url = $config[$storage]['BASE_URL'];
            # 组装数据
            $result['url'] = $base_url . '/' . $result['key'];
            $result['path'] = $result['key'];
            return $result;
        }
        return false;
    }

}